<template>
  <div class="app-container">
    <el-dialog :title="formData.id ? '编辑' : '新增'" :visible.sync="dialogFormVisible">
      <el-form :model="formData" ref="formData" :rules="rules">
        <el-form-item label="角色代码" :label-width="formLabelWidth" prop="roleCode">
          <el-input v-model="formData.roleCode" placeholder="角色代码" autocomplete="off" :disabled="updateRoleCode"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="角色名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="formData.roleDesc" placeholder="角色描述" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('formData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import adminRoleApi from '@/api/core/sys/admin-role'
  export default {
    data () {
      return {
        formData: {
          id: '',
          roleCode: '',
          roleName: '',
          roleDesc: ''
        },
        rules: {
          roleCode: [
            { required: true, message: '请填写角色代码', trigger: 'blur' }
          ],
          roleName: [
            { required: true, message: '请填写角色名称', trigger: 'blur' }
          ]
        },
        dialogFormVisible: false,
        formLabelWidth: '120px',
        updateRoleCode: false
      }
    },
    created () {},
    methods: {
      init(id) {
        this.formData.id = id
        this.dialogFormVisible = true
        if (id) {
          // 查询
          this.updateRoleCode = true
          this.queryById(id)
        } else {
          this.updateRoleCode = false
          this.$nextTick(()=>{
            this.$refs['formData'].resetFields()
          })
        }
      },
      // 查询单个信息
      queryById(id) {
        adminRoleApi.listById(id).then(res => {
          this.formData = res.data.info
          this.formData.updateTime = ''
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            adminRoleApi.saveOrUpdate(this.formData).then(res => {
              if (res.code === 0) {
                this.$message({
                  message: res.message,
                  type: 'success'
                })
                this.dialogFormVisible = false
                this.$emit('refreshDataList')
              }
            }).catch(res => {
              this.$message.error(res.message)
            })
          } else {
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped></style>